package com.hundsun.s3.mrs.core.handler;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hundsun.s3.mrs.core.IParamsIn;
import com.hundsun.s3.mrs.core.IParamsOut;
import com.hundsun.s3.mrs.core.chain.IChain;
import com.hundsun.s3.mrs.core.endpoint.ChannelManager;
import com.hundsun.s3.mrs.core.message.Message;
import com.hundsun.s3.mrs.core.talker.Group;
import com.hundsun.s3.mrs.core.talker.Talker;
import com.hundsun.s3.mrs.core.talker.TalkerManager;
import com.hundsun.s3.mrs.core.task.Task;
import com.hundsun.s3.mrs.core.type.MessageType;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class TextMsgHandler implements IHandler {

	private static final Logger LOG = LoggerFactory.getLogger(TextMsgHandler.class);
	
	@Override
	public void doHandle(IParamsIn in, IParamsOut out, IChain chain) {
		Task task = (Task) in;
		String messageType = task.getMessage().getMessageType();
		if(messageType.equals(MessageType.TYPE_TEXT)) {
			execForText(task);
			chain.setIndex(0);
		} else {
			chain.doHandle(task, null, chain);
		}
	}

	private void execForText(Task task) {
		Message message = task.getMessage();
		String receiverId = message.getReceiverId();
		if(StringUtils.isBlank(receiverId)) {
			LOG.warn("接收人的id为空：" + receiverId);
			return;
		}
		Channel channel;
		TextWebSocketFrame twsf;
		String id;
		Map<String, Group> groupMapper = TalkerManager.getGroupMapper();
		if(groupMapper.containsKey(receiverId)) {
			// 如果是组id，表示是群发任务
			Group group = (Group) groupMapper.get(receiverId);
			if(group == null) {
				LOG.warn("错误的信息格式：指定了一个不存在的组名");
				return;
			}
			List<Talker> member = group.getMember();
			for(Talker talker : member) {
				id = talker.getId();
				if(task.isMyJob(id)) {
					continue;
				}
				channel = ChannelManager.find(id);
				twsf = new TextWebSocketFrame(message.toString());
				channel.writeAndFlush(twsf);
			}
		} else {
			// 单发任务
			channel = ChannelManager.find(receiverId);
			if(channel == null) {
				return;
			}
			twsf = new TextWebSocketFrame(message.toString());
			channel.writeAndFlush(twsf);
		}
	}
}
